from flask import Blueprint, jsonify, request, send_from_directory
from models import User, DoTask, Task
from exts import db

bp = Blueprint("master_manage", __name__, url_prefix="/master_manage")

@bp.route("/master_tasks", methods=["POST", "GET"])
def master_tasks():
    # 获取前端post请求发送来的数据(username,email)
    # 为了获取雇主已发布的任务
    params = request.get_json() # {'email': '123@qq.com', 'username': '406973249'}
    user_item = User.query.filter_by(email=params["email"]).first()
    if user_item.username != params["username"]:
        return "用户不存在", 400
    tasks_ls = Task.query.filter_by(userid=user_item.id).all()
    task_data = []
    for task in tasks_ls:
        if task.audit == 1 and task.taken == 1:
            worker_email = User.query.filter_by(id = task.do_task[0].worker_id).first().email
            task_data_item = {
                "key": task.id,
                "tasktitle": task.tasktitle,
                "bounty": task.bounty,
                "enddate": task.enddate,
                "audit": [task.audit],
                "type_name": task.tasktype.typename,
                "task_res": [task.do_task[0].task_res],
                "email": worker_email, # 雇主用户，返回猎人的email
                "taskintro": task.taskintro,
                "task_evi": task.do_task[0].task_evi
            }
        else:
            task_data_item = {
                "key": task.id,
                "tasktitle": task.tasktitle,
                "bounty": task.bounty,
                "enddate": task.enddate,
                "audit": [task.audit],
                "type_name": task.tasktype.typename,
                "task_res": [0],
                "email": "未领取", # 雇主用户，返回猎人的email
                "taskintro": task.taskintro,
                "task_evi": None
            }
        task_data.append(task_data_item)
    return jsonify({"msg": "请求成功", "task_data": task_data})

@bp.route("/master_change_worker_task_res", methods=["POST", "GET"])
def master_change_worker_task_res():
    # master用户修改任务状态接口
    params = request.get_json() # {'id': 16, 'res': 0} 这个id是task表的id
    task_item = Task.query.filter_by(id = params["id"]).first()
    # print(task_item)
    if task_item is None:
        return "参数错误", 400
    if task_item.do_task[0].task_res == params["res"] and params["res"] != 2:
        # 1、任务修改为已完成
        task_item.do_task[0].task_res = 2
        # 2、对应的猎人增加赏金
        worker_user = User.query.filter_by(id = task_item.do_task[0].worker_id ).first()
        if worker_user is None:
            return "没有该用户", 400
        worker_user_money = worker_user.money
        worker_user.money = worker_user_money + task_item.bounty
        db.session.commit()
        return "修改成功"
    else:
        return "错误请求", 400

@bp.route("/delete_master_task", methods=["POST", "GET"])
def delete_master_task():
    # 雇主删除任务（开发中，已完成任务不能删除）
    # 删除后，将金币返回给用户
    params = request.get_json() # {'id': 16, 'res': 0}
    task_item = Task.query.filter_by(id = params["id"]).first()
    if task_item is None:
        return "参数错误", 400
    if params["res"] == 0:
        # 判断do_task表有没有被领取
        if task_item.taken == 1:
            dotask_item = DoTask.query.filter_by(id = task_item.do_task[0].id).first()
            if dotask_item is None:
                return "参数错误", 400
            if task_item.do_task[0].task_res != params["res"]:
                return "参数错误1", 400
            db.session.delete(dotask_item) # 删除do_task表中的数据
        old_money = task_item.user.money
        task_item.user.money = old_money + task_item.bounty
        db.session.delete(task_item) # 删除task表中的数据
        db.session.commit()
        return "修改成功"
    else:
        return "参数错误", 400

@bp.route("/download_task_evi/<id>/<email>", methods=["POST", "GET"])
def download_task_evi(id, email):
    # 下载任务完成作证材料
    # params = request.get_json() # {'id': 20, 'email': '123@qq.com'}
    params = {"id": id, "email": email}
    user_item = User.query.filter_by(email = params["email"]).first()
    if user_item is None:
        return "no user", 400
    task_item = Task.query.filter_by(id = params["id"]).first()
    if task_item is None or task_item.taken != 1:
        return "no task", 400
    if task_item.user.email != params["email"]:
        return "参数错误", 401
    file_name = task_item.do_task[0].task_evi.split("/")[-1]
    print("file_name is ", file_name)
    print(params)
    return send_from_directory("./public/task_evi/", file_name, as_attachment=True)


@bp.route("/update_task_data", methods=["POST", "GET"])
def update_task_data():
    # 用户修改发布的任务
    # 1、已审核通过的不能修改
    # 2、可修改类目：和发布任务的一样
    params = request.get_json() # {'activate': True, 'id': 6, 'tasktitle': 'php页面开发', 'taskintro': '哈哈哈哈哈', 'typeid': '1', 'bounty': 1000, 'enddate': '2022-03-26', 'email': '143@qq.com', 'username': '616010445'}
    # 特殊的说明：金币如果发生修改，则先返回原本的任务金币给用户，再统一扣除新的金币

    # 验证
    user_item = User.query.filter_by(email = params["email"]).first()
    if user_item is None:
        return "no user", 400
    if params["username"] != user_item.username:
        return "params err", 401
    task_item = Task.query.filter_by(id = params["id"]).first()
    if task_item is None:
        return "no task", 400
    if task_item.audit == 1:
        return "Reviewed and cannot be updated", 403
    if task_item.userid != user_item.id:
        return "params err", 400

    # 修改
    task_item.user.money = task_item.user.money + task_item.bounty - params["bounty"] # 改的总金额
    task_item.bounty = params["bounty"]
    task_item.tasktitle = params["tasktitle"]
    task_item.taskintro = params["taskintro"]
    task_item.enddate = params["enddate"]
    task_item.audit = 0 # 如果是不通过的则改为待审核
    task_item.typeid = params["typeid"]
    db.session.commit()

    return "update success"

